package com.spider.silence.pool;
import com.beust.jcommander.internal.Lists;
import com.spider.silence.downloader.TencentXinWenDownloader;
import com.spider.silence.downloader.WangYiXinWenDownloader;
import com.spider.silence.utils.PropertiesUtil;
import org.apache.log4j.Logger;

import java.util.LinkedList;

/**
 * Created by Linbo Hu on 2017/7/19.
 * 腾讯新闻下载器池
 *
 */
public class TencentXinWenDownloaderPool {

    private Logger logger = Logger.getLogger(TencentXinWenDownloaderPool.class);

    private static final TencentXinWenDownloaderPool INSTANCE = new TencentXinWenDownloaderPool();

    private LinkedList<TencentXinWenDownloader> pool = Lists.newLinkedList();

    private TencentXinWenDownloaderPool() {
        int initNum= Integer.parseInt(PropertiesUtil.getVal("Tencent.DownLoader.Pool.initNum"));
        for(int i = 0; i < initNum; i++) {
            TencentXinWenDownloader downloader = new TencentXinWenDownloader();
            synchronized(pool) {
                pool.add(downloader);
                pool.notifyAll();
            }
        }
    }

    public static TencentXinWenDownloaderPool getInstance() {
        return INSTANCE;
    }

    /**
     * 获取一个下载器
     * @param mills
     * @return
     * @throws InterruptedException
     */
    public TencentXinWenDownloader fetchDownLoader(long mills) throws InterruptedException {
        synchronized(pool) {
            if(mills <= 0) {
                while(pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                long future = System.currentTimeMillis() + mills;
                long remaining = mills;
                while (pool.isEmpty() && remaining > 0) {
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }
                TencentXinWenDownloader downloader = null;
                if(!pool.isEmpty()) {
                    downloader = pool.removeFirst();
                }
                return downloader;
            }
        }
    }

    /**
     * 释放一个下载器
     * @param downloader
     */
    public void releaseDownLoader(TencentXinWenDownloader downloader) {
        if(downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }


}
